/**
 * Created by JasonChou on 16/5/13.
 */
import http from '../libs/http'
import {publish} from '../libs/utils'

var orderService = {
    newInstance: true,
    buySkus: {}
};

var pure = {
    address: null,
    skus: [],
    coupon: null,
    amount: 0,
    postage: {},
    discount: 0,
    remark: '',
    pay: false,
    needPay: 0,
    bill_id: '',
    order_id: ''
};
orderService.pure = pure;

orderService.create = function () {
    this.newInstance = true;
    pure.pay = false;
};

orderService.resume = function (skus) {
    var self = this;

    if (!this.newInstance)
        return;

    this.newInstance = false;
    this.buySkus = skus;


    http.post({
        url: api + 'order/check',
        jsonp: true,
        data: {skus: skus}
    }).then(function (obj) {
        if (obj.code == 0) {
            var data = obj.data;

            pure.needPay = data.needPay;
            pure.address = data.address || null;
            pure.skus = data.skus;
            pure.coupon = data.coupon || null;
            pure.amount = data.amount;
            pure.postage = data.postage;
            pure.discount = data.postage.cost + data.amount - pure.needPay;
        }
    });
};

orderService.changeAddress = function (address) {
    pure.address = address;
};


orderService.changeCoupon = function (coupon, cb) {
    var self = this;

    http.get({
        url: api + 'user/order/coupon/select',
        jsonp: true,
        data: {
            skus: this.buySkus,
            coupon_id: coupon._id
        }
    }).then(function (obj) {
        if (obj.code == 0) {
            var data = obj.data;
            if (data.status == -1)
                return publish('toast', '该优惠券不可用');

            pure.needPay = data.needPay;
            pure.coupon = coupon;
            pure.amount = data.amount;
            pure.discount = data.postage.cost + data.amount - pure.needPay;

            pure.allAmount = pure.needPay + (data.postage.lack ? data.postage.cost : 0)
        }

        cb(obj);
    });


};


export {orderService};
